/**
 * axios
 */
import axios from "axios";
import config from "../config";
import { ElMessage } from "element-plus";
import storage from "./storage";
import router from "@/router";

const TOKEN_INVALID = "token认证失败,请重新登录";
const NETWORK_ERROR = "网络请求异常，请稍后重试";
const USER_ACCOUNT_ERROR = "账号或密码错误,请重新输入";
const USER_LOGIN_ERROR = "用户未登录,请重新登录";
const BUSINESS_ERROR = "业务请求失败";
const PARAM_ERROR = "参数错误";

console.log(config.baseApi);
// 创建axios实例对象,添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
});

// 请求拦截
service.interceptors.request.use((req) => {
  const headers = req.headers;
  console.log(storage.getItem("userInfo"));
  const { token } = storage.getItem("userInfo") || {};
  if (!headers!.Authorization) {
    headers!.Authorization = `Bearer ${token}`;
  }

  return req;
});

// 响应拦截
service.interceptors.response.use((res):any => {
  const { code, data, msg } = res.data;
  console.log("code编码", code);
  if (code === 200) {
    return data;
  } else if (code === 10001) {
    ElMessage.error(msg || PARAM_ERROR);
    return Promise.reject(PARAM_ERROR);
  } else if (code === 20001) {
    ElMessage.error(msg || USER_ACCOUNT_ERROR);
    return Promise.reject(USER_ACCOUNT_ERROR);
  } else if (code === 30001) {
    ElMessage.error(msg || USER_LOGIN_ERROR);
    return Promise.reject(USER_LOGIN_ERROR);
  } else if (code === 40001) {
    ElMessage.error(BUSINESS_ERROR);
    return Promise.reject(BUSINESS_ERROR);
  } else if (code === 50001) {
    ElMessage.error(msg || TOKEN_INVALID);
    // 登录过期跳转到登录页面
    console.log("路由", router);
    setTimeout(() => {
      router.push("/login");
    }, 1500);
    return Promise.reject(TOKEN_INVALID);
  } else {
    ElMessage.error(msg || NETWORK_ERROR);
    return Promise.reject(NETWORK_ERROR);
  }
});

/**
 * 请求的核心函数
 * options 请求配置
 */
function request(options:any) {
  options.method = options.method || "get";
  console.log(options);
  if (options.method.toLowerCase() === "get" && options.data) {
    options.params = options.data;
  }

  let isMock = config.mock;
  if (typeof options.mock != "undefined") {
    isMock = options.mock;
  }

  if (config.env === "prod") {
    service.defaults.baseURL = config.baseApi;
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
  }
  console.log(config, service.defaults);

  return service(options);
}

export default request;
